import { getCurrentInstance, createVNode, render } from 'vue';
import { Modal } from 'ant-design-vue';
import YModal from '@/components/YModal/index.vue';


export const useModal = () => {
  const ins = getCurrentInstance();
  const getContext = () => {
    if (!ins) {
      throw new Error('useModal must be used within a component');
    }
    return ins.appContext;
  };
  const openModal = (content, props = {}) => {

    return new Promise((resolve, reject) => {
      const _context = getContext();
      const container = document.createElement('div');

      const close = () => {
        render(null, container);
        document.body.removeChild(container);
      };
      const confirm = (data) => {
        close();
        resolve();
      };
      const cancel = () => {
        close();
        reject('cancel');
      };
      const { type = "info", title = "提示" } = props;

      // const [modal] = Modal.useModal();
      // Modal[type]({
      //   title,
      //   content,
      //   cancelText: 'No',
      //   onOk: confirm,
      //   onCancel: cancel,
      // })

      const vnode = createVNode(YModal, {
        title,
        content,
        type,
        onConfirm: confirm,
        onCancel: cancel,
      }, {
        default: () => content,
      })
      vnode.appContext = _context;
      render(vnode, container);
      document.body.appendChild(container);
    })
  }
  // 提示
  const info = (content, title = "温馨提示") => {
    return openModal(content, { type: "info", title });

  }
  // 警告提示
  const warning = (content, title = "温馨提示") => {

    return openModal(content, { type: "warning", title });
  }
  // 成功提示
  const success = (content, title = "温馨提示") => {
    return openModal(content, { type: "success", title });
  }
  // 错误提示
  const error = (content, title = "温馨提示") => {
    return openModal(content, { type: "error", title });
  }

  return {
    info,
    warning,
    success,
    error,
  }
};
